#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
商机管理API接口
"""

from flask import Blueprint, request, jsonify, session
from flask_login import login_required, current_user
from datetime import datetime, timedelta
from sqlalchemy import and_, or_
from app import db
from app import (
    BusinessOpportunity, OpportunityStage, OpportunityFollowup, 
    OpportunityStageChange, OpportunityLog, OpportunityProduct, OpportunityCompetitor, User, Customer, Lead
)

# 创建蓝图
business_opportunity_bp = Blueprint('business_opportunity', __name__, url_prefix='/api/opportunity')

# 辅助函数：记录商机操作日志
def log_opportunity_operation(opportunity_id, operation_type, operation_content, operator_id):
    """记录商机操作日志"""
    log = OpportunityLog(
        opportunity_id=opportunity_id,
        operation_type=operation_type,
        operation_content=operation_content,
        operator_id=operator_id
    )
    db.session.add(log)
    db.session.commit()

# 辅助函数：检查用户权限
def check_permission(user_id, opportunity_manager_id, role='user'):
    """检查用户是否有权限操作商机"""
    if role == 'admin':
        return True
    return user_id == opportunity_manager_id

# 获取商机阶段列表
@business_opportunity_bp.route('/stages', methods=['GET'])
@login_required
def get_opportunity_stages():
    """获取商机阶段列表"""
    try:
        stages = OpportunityStage.query.filter_by(is_active=True).order_by(OpportunityStage.order_index).all()
        
        return jsonify({
            'success': True,
            'stages': [
                {
                    'id': stage.id,
                    'name': stage.name,
                    'order_index': stage.order_index,
                    'description': stage.description,
                    'is_default': stage.is_default,
                    'alert_days': stage.alert_days
                } for stage in stages
            ]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取商机阶段失败: {str(e)}'
        }), 500

# 获取商机列表
@business_opportunity_bp.route('/', methods=['GET'])
@login_required
def get_opportunities():
    """获取商机列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        customer_id = request.args.get('customer_id', type=int)
        manager_id = request.args.get('manager_id', type=int)
        stage_id = request.args.get('stage_id', type=int)
        status = request.args.get('status')
        priority = request.args.get('priority')
        keyword = request.args.get('keyword')
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 构建查询
        query = BusinessOpportunity.query
        
        # 非管理员只能看到自己负责的商机
        if not current_user_obj or current_user_obj.role != 'admin':
            query = query.filter_by(manager_id=current_user_id)
        
        # 添加过滤条件
        if customer_id:
            query = query.filter_by(customer_id=customer_id)
        if manager_id:
            query = query.filter_by(manager_id=manager_id)
        if stage_id:
            query = query.filter_by(stage_id=stage_id)
        if status:
            query = query.filter_by(status=status)
        if priority:
            query = query.filter_by(priority=priority)
        if keyword:
            query = query.filter(
                or_(
                    BusinessOpportunity.name.contains(keyword),
                    BusinessOpportunity.description.contains(keyword)
                )
            )
        
        # 分页查询
        opportunities = query.order_by(BusinessOpportunity.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        result = {
            'success': True,
            'opportunities': [
                {
                    'id': opp.id,
                    'name': opp.name,
                    'description': opp.description,
                    'customer_id': opp.customer_id,
                    'customer_name': opp.customer.name if opp.customer else None,
                    'lead_id': opp.lead_id,
                    'lead_name': opp.lead.name if opp.lead else None,
                    'manager_id': opp.manager_id,
                    'owner_name': opp.manager.name if opp.manager else None,
                    'expected_amount': opp.expected_amount,
                    'probability': opp.probability,
                    'expected_close_date': opp.expected_close_date.strftime('%Y-%m-%d') if opp.expected_close_date else None,
                    'stage_id': opp.stage_id,
                    'stage_name': opp.stage.name if opp.stage else None,
                    'status': opp.status,
                    'source': opp.source,
                    'priority': opp.priority,
                    'competitor': opp.competitor,
                    'created_at': opp.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': opp.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                } for opp in opportunities.items
            ],
            'pagination': {
                'current_page': opportunities.page,
                'per_page': opportunities.per_page,
                'total': opportunities.total,
                'total_pages': opportunities.pages,
                'has_prev': opportunities.has_prev,
                'has_next': opportunities.has_next
            }
        }
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取商机列表失败: {str(e)}'
        }), 500

# 获取商机详情
@business_opportunity_bp.route('/<int:opportunity_id>', methods=['GET'])
@login_required
def get_opportunity_detail(opportunity_id):
    """获取商机详情"""
    try:
        # 获取商机信息
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限查看此商机'
            }), 403
        
        # 获取商机跟进记录
        followups = OpportunityFollowup.query.filter_by(opportunity_id=opportunity_id).order_by(
            OpportunityFollowup.created_at.desc()
        ).all()
        
        # 获取商机阶段变更记录
        stage_changes = OpportunityStageChange.query.filter_by(opportunity_id=opportunity_id).order_by(
            OpportunityStageChange.changed_at.desc()
        ).all()
        
        # 获取商机产品
        products = OpportunityProduct.query.filter_by(opportunity_id=opportunity_id).all()
        
        # 获取商机竞争对手
        competitors = OpportunityCompetitor.query.filter_by(opportunity_id=opportunity_id).all()
        
        # 构建返回数据
        result = {
            'success': True,
            'opportunity': {
                'id': opportunity.id,
                'name': opportunity.name,
                'description': opportunity.description,
                'customer_id': opportunity.customer_id,
                'customer_name': opportunity.customer.name if opportunity.customer else None,
                'lead_id': opportunity.lead_id,
                'lead_name': opportunity.lead.name if opportunity.lead else None,
                'manager_id': opportunity.manager_id,
                'owner_name': opportunity.manager.name if opportunity.manager else None,
                'expected_amount': opportunity.expected_amount,
                'probability': opportunity.probability,
                'expected_close_date': opportunity.expected_close_date.strftime('%Y-%m-%d') if opportunity.expected_close_date else None,
                'stage_id': opportunity.stage_id,
                'stage_name': opportunity.stage.name if opportunity.stage else None,
                'status': opportunity.status,
                'source': opportunity.source,
                'priority': opportunity.priority,
                'competitor': opportunity.competitor,
                'lost_reason': opportunity.lost_reason,
                'created_at': opportunity.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': opportunity.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            },
            'followups': [
                {
                    'id': followup.id,
                    'method': followup.method,
                    'content': followup.content,
                    'result': followup.result,
                    'next_followup_time': followup.next_followup_time.strftime('%Y-%m-%d %H:%M:%S') if followup.next_followup_time else None,
                    'manager_id': followup.manager_id,
                    'manager_name': followup.manager.name if followup.manager else None,
                    'created_at': followup.created_at.strftime('%Y-%m-%d %H:%M:%S')
                } for followup in followups
            ],
            'stage_changes': [
                {
                    'id': change.id,
                    'from_stage_id': change.from_stage_id,
                    'from_stage_name': change.from_stage.name if change.from_stage else None,
                    'to_stage_id': change.to_stage_id,
                    'to_stage_name': change.to_stage.name if change.to_stage else None,
                    'change_reason': change.change_reason,
                    'changed_by': change.changed_by,
                    'changed_by_name': change.changed_by_user.name if change.changed_by_user else None,
                    'changed_at': change.changed_at.strftime('%Y-%m-%d %H:%M:%S')
                } for change in stage_changes
            ],
            'products': [
                {
                    'id': product.id,
                    'product_name': product.product_name,
                    'product_description': product.product_description,
                    'quantity': product.quantity,
                    'unit_price': product.unit_price,
                    'total_price': product.total_price,
                    'discount': product.discount,
                    'final_price': product.final_price,
                    'created_at': product.created_at.strftime('%Y-%m-%d %H:%M:%S')
                } for product in products
            ],
            'competitors': [
                {
                    'id': competitor.id,
                    'competitor_name': competitor.competitor_name,
                    'competitor_strength': competitor.competitor_strength,
                    'competitor_weakness': competitor.competitor_weakness,
                    'our_advantage': competitor.our_advantage,
                    'our_disadvantage': competitor.our_disadvantage,
                    'strategy': competitor.strategy,
                    'created_at': competitor.created_at.strftime('%Y-%m-%d %H:%M:%S')
                } for competitor in competitors
            ]
        }
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取商机详情失败: {str(e)}'
        }), 500

# 创建商机
@business_opportunity_bp.route('/', methods=['POST'])
@login_required
def create_opportunity():
    """创建商机"""
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name') or not data.get('customer_id') or not data.get('manager_id'):
            return jsonify({
                'success': False,
                'message': '商机名称、客户和负责人不能为空'
            }), 400
        
        # 验证客户是否存在
        customer = Customer.query.get(data['customer_id'])
        if not customer:
            return jsonify({
                'success': False,
                'message': '客户不存在'
            }), 400
        
        # 验证负责人是否存在
        manager = User.query.get(data['manager_id'])
        if not manager:
            return jsonify({
                'success': False,
                'message': '负责人不存在'
            }), 400
        
        # 验证阶段是否存在
        stage = OpportunityStage.query.get(data.get('stage_id'))
        if not stage:
            # 如果没有指定阶段，使用默认阶段
            default_stage = OpportunityStage.query.filter_by(is_default=True).first()
            if not default_stage:
                default_stage = OpportunityStage.query.first()
            stage_id = default_stage.id if default_stage else 1
        else:
            stage_id = stage.id
        
        # 创建商机
        opportunity = BusinessOpportunity(
            name=data['name'],
            description=data.get('description', ''),
            customer_id=data['customer_id'],
            lead_id=data.get('lead_id'),
            manager_id=data['manager_id'],
            expected_amount=float(data.get('expected_amount', 0)),
            probability=int(data.get('probability', 0)),
            expected_close_date=datetime.strptime(data['expected_close_date'], '%Y-%m-%d').date() if data.get('expected_close_date') else None,
            stage_id=stage_id,
            status=data.get('status', '活跃'),
            source=data.get('source', '直接创建'),
            priority=data.get('priority', '中'),
            competitor=data.get('competitor', '')
        )
        
        db.session.add(opportunity)
        db.session.commit()
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '创建商机', 
            f'创建了商机：{opportunity.name}', 
            current_user.id if current_user.is_authenticated else 0
        )
        
        # 如果有线索ID，更新线索状态为已转化
        if data.get('lead_id'):
            lead = Lead.query.get(data['lead_id'])
            if lead:
                lead.status = '已转化'
                db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '商机创建成功',
            'opportunity_id': opportunity.id
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'创建商机失败: {str(e)}'
        }), 500

# 更新商机
@business_opportunity_bp.route('/<int:opportunity_id>', methods=['PUT'])
@login_required
def update_opportunity(opportunity_id):
    """更新商机"""
    try:
        # 获取商机
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限更新此商机'
            }), 403
        
        # 获取请求数据
        data = request.get_json()
        
        # 记录原始阶段ID
        original_stage_id = opportunity.stage_id
        
        # 更新商机信息
        if 'name' in data:
            opportunity.name = data['name']
        if 'description' in data:
            opportunity.description = data['description']
        if 'customer_id' in data:
            # 验证客户是否存在
            customer = Customer.query.get(data['customer_id'])
            if not customer:
                return jsonify({
                    'success': False,
                    'message': '客户不存在'
                }), 400
            opportunity.customer_id = data['customer_id']
        if 'lead_id' in data:
            opportunity.lead_id = data['lead_id']
        if 'manager_id' in data:
            # 验证负责人是否存在
            manager = User.query.get(data['manager_id'])
            if not manager:
                return jsonify({
                    'success': False,
                    'message': '负责人不存在'
                }), 400
            opportunity.manager_id = data['manager_id']
        if 'expected_amount' in data:
            opportunity.expected_amount = float(data['expected_amount'])
        if 'probability' in data:
            opportunity.probability = int(data['probability'])
        if 'expected_close_date' in data:
            opportunity.expected_close_date = datetime.strptime(data['expected_close_date'], '%Y-%m-%d').date() if data['expected_close_date'] else None
        if 'stage_id' in data:
            # 验证阶段是否存在
            stage = OpportunityStage.query.get(data['stage_id'])
            if not stage:
                return jsonify({
                    'success': False,
                    'message': '商机阶段不存在'
                }), 400
            opportunity.stage_id = data['stage_id']
        if 'status' in data:
            opportunity.status = data['status']
        if 'source' in data:
            opportunity.source = data['source']
        if 'priority' in data:
            opportunity.priority = data['priority']
        if 'competitor' in data:
            opportunity.competitor = data['competitor']
        if 'lost_reason' in data:
            opportunity.lost_reason = data['lost_reason']
        
        opportunity.updated_at = datetime.now()
        
        db.session.commit()
        
        # 如果阶段发生变化，记录阶段变更
        if original_stage_id != opportunity.stage_id:
            stage_change = OpportunityStageChange(
                opportunity_id=opportunity.id,
                from_stage_id=original_stage_id,
                to_stage_id=opportunity.stage_id,
                change_reason=data.get('stage_change_reason', ''),
                changed_by=current_user_id
            )
            db.session.add(stage_change)
            db.session.commit()
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '更新商机', 
            f'更新了商机：{opportunity.name}', 
            current_user_id
        )
        
        return jsonify({
            'success': True,
            'message': '商机更新成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新商机失败: {str(e)}'
        }), 500

# 删除商机
@business_opportunity_bp.route('/<int:opportunity_id>', methods=['DELETE'])
@login_required
def delete_opportunity(opportunity_id):
    """删除商机"""
    try:
        # 获取商机
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限删除此商机'
            }), 403
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '删除商机', 
            f'删除了商机：{opportunity.name}', 
            current_user_id
        )
        
        # 删除商机
        db.session.delete(opportunity)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '商机删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'删除商机失败: {str(e)}'
        }), 500

# 添加商机跟进记录
@business_opportunity_bp.route('/<int:opportunity_id>/followup', methods=['POST'])
@login_required
def add_opportunity_followup(opportunity_id):
    """添加商机跟进记录"""
    try:
        # 获取商机
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限添加此商机的跟进记录'
            }), 403
        
        # 获取请求数据
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('content'):
            return jsonify({
                'success': False,
                'message': '跟进内容不能为空'
            }), 400
        
        # 创建跟进记录
        followup = OpportunityFollowup(
            opportunity_id=opportunity_id,
            manager_id=current_user_id,
            method=data.get('method', '电话'),
            content=data['content'],
            result=data.get('result', ''),
            next_followup_time=datetime.strptime(data['next_followup_time'], '%Y-%m-%d %H:%M:%S') if data.get('next_followup_time') else None
        )
        
        db.session.add(followup)
        db.session.commit()
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '添加跟进记录', 
            f'添加了商机跟进记录：{data["content"][:50]}...', 
            current_user_id
        )
        
        return jsonify({
            'success': True,
            'message': '跟进记录添加成功',
            'followup_id': followup.id
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'添加跟进记录失败: {str(e)}'
        }), 500

# 添加商机产品
@business_opportunity_bp.route('/<int:opportunity_id>/product', methods=['POST'])
@login_required
def add_opportunity_product(opportunity_id):
    """添加商机产品"""
    try:
        # 获取商机
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限添加此商机的产品'
            }), 403
        
        # 获取请求数据
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('product_name'):
            return jsonify({
                'success': False,
                'message': '产品名称不能为空'
            }), 400
        
        # 计算最终价格
        quantity = int(data.get('quantity', 1))
        unit_price = float(data.get('unit_price', 0))
        discount = float(data.get('discount', 0))
        total_price = quantity * unit_price
        final_price = total_price * (1 - discount / 100)
        
        # 创建产品
        product = OpportunityProduct(
            opportunity_id=opportunity_id,
            product_name=data['product_name'],
            product_description=data.get('product_description', ''),
            quantity=quantity,
            unit_price=unit_price,
            total_price=total_price,
            discount=discount,
            final_price=final_price
        )
        
        db.session.add(product)
        db.session.commit()
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '添加产品', 
            f'添加了商机产品：{data["product_name"]}', 
            current_user_id
        )
        
        return jsonify({
            'success': True,
            'message': '产品添加成功',
            'product_id': product.id
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'添加产品失败: {str(e)}'
        }), 500

# 添加商机竞争对手
@business_opportunity_bp.route('/<int:opportunity_id>/competitor', methods=['POST'])
@login_required
def add_opportunity_competitor(opportunity_id):
    """添加商机竞争对手"""
    try:
        # 获取商机
        opportunity = BusinessOpportunity.query.get_or_404(opportunity_id)
        
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 检查权限
        if not check_permission(current_user_id, opportunity.manager_id, current_user_obj.role if current_user_obj else 'user'):
            return jsonify({
                'success': False,
                'message': '您没有权限添加此商机的竞争对手'
            }), 403
        
        # 获取请求数据
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('competitor_name'):
            return jsonify({
                'success': False,
                'message': '竞争对手名称不能为空'
            }), 400
        
        # 创建竞争对手
        competitor = OpportunityCompetitor(
            opportunity_id=opportunity_id,
            competitor_name=data['competitor_name'],
            competitor_strength=data.get('competitor_strength', ''),
            competitor_weakness=data.get('competitor_weakness', ''),
            our_advantage=data.get('our_advantage', ''),
            our_disadvantage=data.get('our_disadvantage', ''),
            strategy=data.get('strategy', '')
        )
        
        db.session.add(competitor)
        db.session.commit()
        
        # 记录操作日志
        log_opportunity_operation(
            opportunity.id, '添加竞争对手', 
            f'添加了商机竞争对手：{data["competitor_name"]}', 
            current_user_id
        )
        
        return jsonify({
            'success': True,
            'message': '竞争对手添加成功',
            'competitor_id': competitor.id
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'添加竞争对手失败: {str(e)}'
        }), 500

# 获取商机统计数据
@business_opportunity_bp.route('/statistics', methods=['GET'])
@login_required
def get_opportunity_statistics():
    """获取商机统计数据"""
    try:
        # 获取当前用户信息
        current_user_id = current_user.id if current_user.is_authenticated else None
        current_user_obj = current_user
        
        # 构建查询
        query = BusinessOpportunity.query
        
        # 非管理员只能看到自己负责的商机
        if not current_user_obj or current_user_obj.role != 'admin':
            query = query.filter_by(manager_id=current_user_id)
        
        # 总商机数
        total_opportunities = query.count()
        
        # 按状态统计
        status_stats = {}
        for status in ['活跃', '暂停', '关闭', '赢单', '输单']:
            count = query.filter_by(status=status).count()
            status_stats[status] = count
        
        # 按阶段统计
        stage_stats = {}
        stages = OpportunityStage.query.filter_by(is_active=True).order_by(OpportunityStage.order_index).all()
        for stage in stages:
            count = query.filter_by(stage_id=stage.id).count()
            stage_stats[stage.name] = count
        
        # 按优先级统计
        priority_stats = {}
        for priority in ['低', '中', '高']:
            count = query.filter_by(priority=priority).count()
            priority_stats[priority] = count
        
        # 预计成交金额统计
        total_expected_amount = db.session.query(db.func.sum(BusinessOpportunity.expected_amount)).filter(
            BusinessOpportunity.status.in_(['活跃', '暂停'])
        )
        if not current_user_obj or current_user_obj.role != 'admin':
            total_expected_amount = total_expected_amount.filter_by(manager_id=current_user_id)
        total_expected_amount = total_expected_amount.scalar() or 0
        
        # 本月新增商机数
        current_month = datetime.now().replace(day=1)
        month_opportunities = query.filter(BusinessOpportunity.created_at >= current_month).count()
        
        # 本月赢单数
        month_won = query.filter(
            and_(
                BusinessOpportunity.status == '赢单',
                BusinessOpportunity.updated_at >= current_month
            )
        ).count()
        
        # 本月输单数
        month_lost = query.filter(
            and_(
                BusinessOpportunity.status == '输单',
                BusinessOpportunity.updated_at >= current_month
            )
        ).count()
        
        # 转化率
        conversion_rate = 0
        if total_opportunities > 0:
            conversion_rate = round((month_won / total_opportunities) * 100, 2)
        
        return jsonify({
            'success': True,
            'statistics': {
                'total': total_opportunities,
                'won': status_stats.get('赢单', 0),
                'lost': status_stats.get('输单', 0),
                'active': status_stats.get('活跃', 0),
                'total_amount': total_expected_amount,
                'status_stats': status_stats,
                'stage_stats': stage_stats,
                'priority_stats': priority_stats,
                'month_opportunities': month_opportunities,
                'month_won': month_won,
                'month_lost': month_lost,
                'conversion_rate': conversion_rate
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取商机统计数据失败: {str(e)}'
        }), 500

# 获取客户列表
@business_opportunity_bp.route('/customers', methods=['GET'])
@login_required
def get_customers():
    """获取客户列表"""
    try:
        customers = Customer.query.filter_by(status='活跃').order_by(Customer.name).all()
        
        return jsonify({
            'success': True,
            'customers': [
                {
                    'id': customer.id,
                    'name': customer.name,
                    'phone': customer.phone,
                    'email': customer.email
                } for customer in customers
            ]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取客户列表失败: {str(e)}'
        }), 500

# 获取用户列表
@business_opportunity_bp.route('/users', methods=['GET'])
@login_required
def get_users():
    """获取用户列表"""
    try:
        users = User.query.filter_by(is_active=True).order_by(User.name).all()
        
        return jsonify({
            'success': True,
            'users': [
                {
                    'id': user.id,
                    'name': user.name,
                    'department': user.department,
                    'position': user.position
                } for user in users
            ]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取用户列表失败: {str(e)}'
        }), 500